package com.huanxing.cloud.auth.config;

import com.huanxing.cloud.common.core.constant.CacheConstants;
import com.huanxing.cloud.common.security.component.HuanxingWebResponseExceptionTranslator;
import com.huanxing.cloud.common.security.service.HuanxingUserDetailsService;
import com.huanxing.cloud.common.security.service.RedisClientDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

/** 认证服务配置 @Author lijx @Date 2022/1/26 16:03 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

  private final AuthenticationManager authenticationManager;

  private final DataSource dataSource;

  private final RedisConnectionFactory redisConnectionFactory;

  private final HuanxingUserDetailsService userDetailsService;

  /** 定义授权和令牌端点以及令牌服务 */
  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints
        // 请求方式
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
        // 指定token存储位置
        .tokenStore(tokenStore())
        // token增强
        .tokenEnhancer(tokenEnhancer())
        // 用户账号密码认证
        .userDetailsService(userDetailsService)
        // 指定认证管理器
        .authenticationManager(authenticationManager)
        // 是否重复使用 refresh_token
        .reuseRefreshTokens(false)
        .pathMapping("/oauth/confirm_access", "/token/confirm_access")
        // 自定义异常处理
        .exceptionTranslator(new HuanxingWebResponseExceptionTranslator());
  }

  /** 配置令牌端点(Token Endpoint)的安全约束 */
  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer.allowFormAuthenticationForClients().checkTokenAccess("isAuthenticated()");
  }

  /** 声明 ClientDetails实现 */
  public RedisClientDetailsService clientDetailsService() {
    RedisClientDetailsService clientDetailsService = new RedisClientDetailsService(dataSource);
    return clientDetailsService;
  }

  /** 配置客户端详情 */
  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(clientDetailsService());
  }

  /** 基于 Redis 实现，令牌保存到缓存 */
  @Bean
  public TokenStore tokenStore() {
    RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
    tokenStore.setPrefix(CacheConstants.OAUTH_ACCESS);
    return tokenStore;
  }

  /** token增强 */
  @Bean
  public TokenEnhancer tokenEnhancer() {
    return new HuanxingTokenEnhancer();
  }
}
